import redis
import json
from django.http import JsonResponse
from django.views.decorators.http import require_http_methods
import pandas as pd
from prophet import Prophet
import os

def load_data():
    file_path = '每小时进出港统计.xlsx'
    df = pd.read_excel(file_path, engine='openpyxl')
    df['时间'] = pd.to_datetime(df['时间'])
    return df.rename(columns={'时间': 'ds', '进出港次数': 'y'})

def train_model(df):
    model = Prophet(
        seasonality_mode='additive',
        seasonality_prior_scale=10.0,
        changepoint_prior_scale=0.5,
        n_changepoints=30,
        interval_width=0.8
    )
    model.add_seasonality(name='daily', period=24, fourier_order=10)
    model.fit(df)
    return model

def predict(model, periods=24, freq='h'):
    future = model.make_future_dataframe(periods=periods, freq=freq)
    forecast = model.predict(future)
    forecast['yhat'] = forecast['yhat'].clip(lower=0)
    forecast['yhat_lower'] = forecast['yhat_lower'].clip(lower=0)
    forecast['yhat_upper'] = forecast['yhat_upper'].clip(lower=0)
    return forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']]

# 配置Redis连接
redis_client = redis.StrictRedis(host='106.14.88.143', port=6379, db=0, password='redis')

@require_http_methods(["GET"])
def gethourly(request):
    # 从Redis中获取数据
    data = redis_client.get('hourly_data')
    if data:
        formatted_data = json.loads(data)
    else:
        # 如果Redis中没有数据，则调用sethourly方法生成数据并存储到Redis中
        sethourly(request)  # 修改: 传递request参数
        formatted_data = json.loads(redis_client.get('hourly_data'))
    return JsonResponse(formatted_data, safe=False, json_dumps_params={'ensure_ascii': False})

@require_http_methods(["GET"])
def sethourly(request):
    # 调用sethourly方法来生成并存储数据
    df = load_data()
    model = train_model(df)
    forecast = predict(model)

    # 只保留最后48条记录
    forecast = forecast.tail(48)

    # 将DataFrame转换为适合ECharts的数据格式
    data = forecast.to_dict(orient='records')
    formatted_data = [
        {
            'date': row['ds'].strftime('%Y-%m-%d %H:%M:%S'),
            'value': row['yhat'],
            'l': row['yhat_lower'],
            'u': row['yhat_upper']
        }
        for row in data
    ]

    # 将数据存储到Redis中
    redis_client.set('hourly_data', json.dumps(formatted_data))
    return JsonResponse("每小时预测内容生成成功", safe=False, json_dumps_params={'ensure_ascii': False})